{% extends 'base.html' %}

{% block title %}耗材记录管理 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    /* 现代化卡片样式 */
    .stats-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        border-radius: 15px;
        color: white;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.15);
    }
    
    .stats-card.success {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }
    
    .stats-card.danger {
        background: linear-gradient(135deg, #fc466b 0%, #3f5efb 100%);
    }
    
    .stats-card.info {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    .stats-card.warning {
        background: linear-gradient(135deg, #FDBB2D 0%, #22C1C3 100%);
    }

    /* 操作类型徽章样式 */
    .transaction-badge {
        font-size: 0.85rem;
        padding: 0.5rem 0.8rem;
        border-radius: 0.6rem;
        font-weight: 700;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        border: 2px solid transparent;
        display: inline-flex;
        align-items: center;
        gap: 0.3rem;
        min-width: 80px;
        justify-content: center;
    }

    .transaction-in {
        background: linear-gradient(135deg, #198754, #20c997);
        color: #ffffff;
        border-color: #146c43;
        box-shadow: 0 3px 6px rgba(25, 135, 84, 0.4);
    }

    .transaction-out {
        background: linear-gradient(135deg, #dc3545, #e85d75);
        color: #ffffff;
        border-color: #b02a37;
        box-shadow: 0 3px 6px rgba(220, 53, 69, 0.4);
    }

    .transaction-adjust {
        background: linear-gradient(135deg, #0dcaf0, #6f42c1);
        color: #ffffff;
        border-color: #0aa2c0;
        box-shadow: 0 3px 6px rgba(13, 202, 240, 0.4);
    }

    /* 搜索和筛选区域 */
    .filter-section {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 15px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    /* 表格样式优化 */
    .table-modern {
        background: white;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .table-modern thead th {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        font-weight: 600;
        padding: 1rem 0.75rem;
    }

    .table-modern tbody tr {
        transition: all 0.3s ease;
    }

    .table-modern tbody tr:hover {
        background-color: #f8f9fa;
        transform: scale(1.01);
    }

    /* 数量显示样式 */
    .quantity-display {
        font-weight: 700;
        font-size: 1.1rem;
    }

    .quantity-in {
        color: #198754;
    }

    .quantity-out {
        color: #dc3545;
    }

    /* 操作按钮组 */
    .action-buttons .btn {
        border-radius: 8px;
        transition: all 0.3s ease;
    }

    .action-buttons .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }

    /* 分页样式 */
    .pagination .page-link {
        border-radius: 8px;
        margin: 0 2px;
        border: none;
        color: #667eea;
    }

    .pagination .page-item.active .page-link {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }

    /* 响应式优化 */
    @media (max-width: 768px) {
        .filter-section {
            padding: 1rem;
        }
        
        .stats-card {
            margin-bottom: 1rem;
        }
        
        .table-responsive {
            font-size: 0.9rem;
        }
        
        .transaction-badge {
            font-size: 0.75rem;
            padding: 0.3rem 0.5rem;
            min-width: 60px;
        }
        
        /* 移动端隐藏部分列 */
        .table th:nth-child(5),
        .table td:nth-child(5),
        .table th:nth-child(9),
        .table td:nth-child(9) {
            display: none;
        }
        
        .action-buttons .btn-group {
            flex-direction: column;
        }
        
        .action-buttons .btn {
            margin-bottom: 0.25rem;
        }
    }
    
    @media (max-width: 576px) {
        .table th:nth-child(7),
        .table td:nth-child(7) {
            display: none;
        }
        
        .filter-section .row > div {
            margin-bottom: 1rem;
        }
    }
    
    /* 表格行选中效果 */
    .table tbody tr.selected {
        background-color: #e3f2fd !important;
        border-left: 4px solid #2196f3;
    }
    
    /* 操作按钮悬停效果 */
    .action-buttons .btn-outline-info:hover {
        background-color: #17a2b8;
        border-color: #17a2b8;
        color: white;
    }
    
    .action-buttons .btn-outline-danger:hover {
        background-color: #dc3545;
        border-color: #dc3545;
        color: white;
    }
    
    /* 模态框样式优化 */
    .modal-content {
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    }
    
    .modal-header {
        border-radius: 15px 15px 0 0;
    }
    
    /* 徽章样式优化 */
    .badge {
        font-weight: 500;
        letter-spacing: 0.5px;
    }
    
    /* 描述编辑区域样式 */
    .description-cell {
        position: relative;
    }
    
    .description-cell:hover .edit-description-btn {
        opacity: 1;
    }
    
    .edit-description-btn {
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    /* 统计卡片动画 */
    .stats-card {
        animation: fadeInUp 0.6s ease-out;
    }
    
    .stats-card:nth-child(1) { animation-delay: 0.1s; }
    .stats-card:nth-child(2) { animation-delay: 0.2s; }
    .stats-card:nth-child(3) { animation-delay: 0.3s; }
    .stats-card:nth-child(4) { animation-delay: 0.4s; }
    
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* 空状态样式 */
    .empty-state {
        text-align: center;
        padding: 3rem;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    /* 加载动画 */
    .loading-spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题和面包屑 -->
    <div class="row mb-4">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'assets:consumable_list' %}">耗材管理</a></li>
                    <li class="breadcrumb-item active" aria-current="page">耗材记录管理</li>
                </ol>
            </nav>
            
            <div class="d-flex justify-content-between align-items-center">
                <h2 class="mb-0">
                    <i class="fas fa-history me-2 text-primary"></i>耗材记录管理
                </h2>
                <div class="btn-group">
                    <button type="button" class="btn btn-success" onclick="exportRecords()" title="导出当前筛选结果">
                        <i class="fas fa-download me-1"></i>导出记录
                    </button>
                    <button type="button" class="btn btn-info" onclick="showQuickStats()" title="查看快速统计">
                        <i class="fas fa-chart-bar me-1"></i>统计分析
                    </button>
                    <button type="button" class="btn btn-primary" onclick="refreshData()" title="刷新页面数据">
                        <i class="fas fa-sync-alt me-1"></i>刷新数据
                    </button>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" title="更多操作">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="{% url 'assets:consumable_list' %}">
                                <i class="fas fa-boxes me-2"></i>耗材管理
                            </a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:warehouse_list' %}">
                                <i class="fas fa-warehouse me-2"></i>仓库管理
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="showHelp()">
                                <i class="fas fa-question-circle me-2"></i>使用帮助
                            </a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stats-card info">
                <div class="card-body text-center">
                    <i class="fas fa-list-alt fa-2x mb-2"></i>
                    <h3 class="mb-1">{{ total_logs|default:0 }}</h3>
                    <p class="mb-0">总记录数</p>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stats-card success">
                <div class="card-body text-center">
                    <i class="fas fa-arrow-down fa-2x mb-2"></i>
                    <h3 class="mb-1">{{ total_in_logs|default:0 }}</h3>
                    <p class="mb-0">入库记录</p>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stats-card danger">
                <div class="card-body text-center">
                    <i class="fas fa-arrow-up fa-2x mb-2"></i>
                    <h3 class="mb-1">{{ total_out_logs|default:0 }}</h3>
                    <p class="mb-0">出库记录</p>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stats-card warning">
                <div class="card-body text-center">
                    <i class="fas fa-calendar-day fa-2x mb-2"></i>
                    <h3 class="mb-1">{{ today_logs|default:0 }}</h3>
                    <p class="mb-0">今日记录</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
        <form method="get" class="row g-3" id="filterForm">
            <div class="col-lg-3 col-md-6">
                <label for="search" class="form-label">
                    <i class="fas fa-search me-1"></i>搜索耗材
                </label>
                <input type="text" class="form-control" id="search" name="search" 
                       value="{{ search_query }}" placeholder="输入耗材名称或编码">
            </div>
            
            <div class="col-lg-2 col-md-6">
                <label for="transaction_type" class="form-label">
                    <i class="fas fa-filter me-1"></i>操作类型
                </label>
                <select class="form-select" id="transaction_type" name="transaction_type">
                    <option value="">全部类型</option>
                    <option value="in" {% if transaction_type == 'in' %}selected{% endif %}>入库</option>
                    <option value="out" {% if transaction_type == 'out' %}selected{% endif %}>出库</option>
                </select>
            </div>
            
            <div class="col-lg-2 col-md-6">
                <label for="operator" class="form-label">
                    <i class="fas fa-user me-1"></i>操作人
                </label>
                <select class="form-select" id="operator" name="operator">
                    <option value="">全部操作人</option>
                    {% for operator in operators %}
                    <option value="{{ operator.id }}" {% if request.GET.operator == operator.id|stringformat:"s" %}selected{% endif %}>
                        {{ operator.get_full_name|default:operator.username }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            
            <div class="col-lg-2 col-md-6">
                <label for="warehouse" class="form-label">
                    <i class="fas fa-warehouse me-1"></i>仓库
                </label>
                <select class="form-select" id="warehouse" name="warehouse">
                    <option value="">全部仓库</option>
                    {% for warehouse in warehouses %}
                    <option value="{{ warehouse.id }}" {% if request.GET.warehouse == warehouse.id|stringformat:"s" %}selected{% endif %}>
                        {{ warehouse.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            
            <div class="col-lg-2 col-md-6">
                <label for="date_range" class="form-label">
                    <i class="fas fa-calendar me-1"></i>时间范围
                </label>
                <select class="form-select" id="date_range" name="date_range">
                    <option value="">全部时间</option>
                    <option value="today" {% if request.GET.date_range == 'today' %}selected{% endif %}>今天</option>
                    <option value="week" {% if request.GET.date_range == 'week' %}selected{% endif %}>本周</option>
                    <option value="month" {% if request.GET.date_range == 'month' %}selected{% endif %}>本月</option>
                    <option value="quarter" {% if request.GET.date_range == 'quarter' %}selected{% endif %}>本季度</option>
                </select>
            </div>
            
            <div class="col-lg-1 col-md-6 d-flex align-items-end">
                <div class="btn-group w-100">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i>
                    </button>
                    <a href="{% url 'assets:inventory_log_list' %}" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i>
                    </a>
                </div>
            </div>
        </form>
    </div>

    <!-- 记录列表 -->
    <div class="card table-modern">
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2"></i>记录列表
                    {% if search_query or transaction_type or request.GET.operator or request.GET.warehouse or request.GET.date_range %}
                    <small class="text-muted">(已筛选)</small>
                    {% endif %}
                </h5>
                <div class="d-flex align-items-center">
                    <span class="text-muted me-3">共 {{ page_obj.paginator.count }} 条记录</span>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-danger" onclick="batchDelete()" disabled id="batchDeleteBtn">
                            <i class="fas fa-trash me-1"></i>批量删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card-body p-0">
            {% if page_obj %}
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th width="3%">
                                <input type="checkbox" class="form-check-input" id="selectAllCheckbox" onchange="toggleSelectAll()">
                            </th>
                            <th width="10%">操作类型</th>
                            <th width="15%">耗材信息</th>
                            <th width="10%">数量变化</th>
                            <th width="8%">库存余额</th>
                            <th width="10%">操作人</th>
                            <th width="20%">操作描述</th>
                            <th width="12%">操作时间</th>
                            <th width="8%">仓库</th>
                            <th width="4%">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for log in page_obj %}
                        <tr data-log-id="{{ log.id }}">
                            <td>
                                <input type="checkbox" class="form-check-input record-checkbox" value="{{ log.id }}">
                            </td>
                            <td>
                                {% if log.transaction_type == "in" %}
                                <span class="transaction-badge transaction-in">
                                    <i class="fas fa-arrow-down"></i>入库
                                </span>
                                {% elif log.transaction_type == "out" %}
                                <span class="transaction-badge transaction-out">
                                    <i class="fas fa-arrow-up"></i>出库
                                </span>
                                {% else %}
                                <span class="transaction-badge transaction-adjust">
                                    <i class="fas fa-exchange-alt"></i>调整
                                </span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="d-flex flex-column">
                                    <strong class="text-primary">{{ log.consumable.name }}</strong>
                                    <small class="text-muted">
                                        <i class="fas fa-barcode me-1"></i>{{ log.consumable.code }}
                                    </small>
                                    {% if log.consumable.model %}
                                    <small class="text-info">
                                        <i class="fas fa-tag me-1"></i>{{ log.consumable.model }}
                                    </small>
                                    {% endif %}
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    {% if log.transaction_type == "in" %}
                                    <span class="quantity-display quantity-in">+{{ log.quantity }}</span>
                                    {% elif log.transaction_type == "out" %}
                                    <span class="quantity-display quantity-out">-{{ log.quantity }}</span>
                                    {% else %}
                                    <span class="quantity-display text-info">{{ log.quantity }}</span>
                                    {% endif %}
                                    <small class="text-muted ms-1">{{ log.consumable.unit }}</small>
                                </div>
                            </td>
                            <td>
                                {% if log.remaining_quantity is not None %}
                                <span class="badge bg-light text-dark fs-6">
                                    {{ log.remaining_quantity }} {{ log.consumable.unit }}
                                </span>
                                {% else %}
                                <span class="text-muted">-</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if log.operator %}
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-user-circle me-2 text-info"></i>
                                    <div>
                                        <div class="fw-bold">{{ log.operator.get_full_name|default:log.operator.username }}</div>
                                        <small class="text-muted">{{ log.operator.username }}</small>
                                    </div>
                                </div>
                                {% else %}
                                <div class="d-flex align-items-center text-muted">
                                    <i class="fas fa-robot me-2"></i>
                                    <span>系统操作</span>
                                </div>
                                {% endif %}
                            </td>
                            <td>
                                <div class="description-cell" data-log-id="{{ log.id }}">
                                    {% if log.description %}
                                    <span class="description-text" title="{{ log.description }}">
                                        {{ log.description|truncatechars:50 }}
                                    </span>
                                    {% else %}
                                    <span class="text-muted description-text">暂无描述</span>
                                    {% endif %}
                                    {% if log.operator == request.user or request.user.is_superuser %}
                                    <button type="button" class="btn btn-link btn-sm p-0 ms-2 edit-description-btn" 
                                            onclick="editDescription({{ log.id }})" title="编辑描述">
                                        <i class="fas fa-edit text-primary"></i>
                                    </button>
                                    {% endif %}
                                </div>
                            </td>
                            <td>
                                <div class="d-flex flex-column">
                                    <span class="fw-bold">{{ log.created_at|date:"Y-m-d" }}</span>
                                    <small class="text-muted">{{ log.created_at|date:"H:i:s" }}</small>
                                </div>
                            </td>
                            <td>
                                {% if log.consumable.warehouse %}
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-warehouse me-1 text-success"></i>
                                    <span title="{{ log.consumable.warehouse.name }}">
                                        {{ log.consumable.warehouse.name|truncatechars:10 }}
                                    </span>
                                </div>
                                {% else %}
                                <span class="text-muted">-</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <div class="btn-group btn-group-sm">
                                        <button type="button" class="btn btn-outline-info" 
                                                onclick="showLogDetail({{ log.id }})" title="查看详情">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        {% if log.operator == request.user or request.user.is_superuser %}
                                        <button type="button" class="btn btn-outline-danger" 
                                                onclick="deleteLog({{ log.id }})" title="删除记录">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% else %}
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <h4>暂无记录</h4>
                <p class="text-muted">没有找到符合条件的耗材记录</p>
                <a href="{% url 'assets:consumable_list' %}" class="btn btn-primary">
                    <i class="fas fa-plus me-1"></i>去添加耗材
                </a>
            </div>
            {% endif %}
        </div>
        
        <!-- 分页 -->
        {% if page_obj.has_other_pages %}
        <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted">
                    显示第 {{ page_obj.start_index }} - {{ page_obj.end_index }} 条，共 {{ page_obj.paginator.count }} 条记录
                </div>
                <nav aria-label="记录分页">
                    <ul class="pagination mb-0">
                        {% if page_obj.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page=1">
                                <i class="fas fa-angle-double-left"></i>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.previous_page_number }}">
                                <i class="fas fa-angle-left"></i>
                            </a>
                        </li>
                        {% endif %}
                        
                        {% for num in page_obj.paginator.page_range %}
                        {% if page_obj.number == num %}
                        <li class="page-item active">
                            <span class="page-link">{{ num }}</span>
                        </li>
                        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ num }}">{{ num }}</a>
                        </li>
                        {% endif %}
                        {% endfor %}
                        
                        {% if page_obj.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.next_page_number }}">
                                <i class="fas fa-angle-right"></i>
                            </a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.paginator.num_pages }}">
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                </nav>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- 记录详情模态框 -->
<div class="modal fade" id="logDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-info-circle me-2"></i>记录详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="logDetailContent">
                <div class="text-center">
                    <div class="loading-spinner"></div>
                    <p class="mt-2">加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 编辑描述模态框 -->
<div class="modal fade" id="editDescriptionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-edit me-2"></i>编辑记录描述
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" id="editDescriptionForm">
                {% csrf_token %}
                <input type="hidden" name="action" value="edit_description">
                <input type="hidden" name="log_id" id="editLogId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="editDescription" class="form-label">记录描述</label>
                        <textarea class="form-control" id="editDescription" name="description" rows="4" 
                                  placeholder="请输入操作描述..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全选功能
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    const recordCheckboxes = document.querySelectorAll('.record-checkbox');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    recordCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    
    updateBatchDeleteButton();
}

function selectAll() {
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    selectAllCheckbox.checked = true;
    toggleSelectAll();
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const checkedBoxes = document.querySelectorAll('.record-checkbox:checked');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    if (checkedBoxes.length > 0) {
        batchDeleteBtn.disabled = false;
        batchDeleteBtn.innerHTML = `<i class="fas fa-trash me-1"></i>批量删除 (${checkedBoxes.length})`;
    } else {
        batchDeleteBtn.disabled = true;
        batchDeleteBtn.innerHTML = '<i class="fas fa-trash me-1"></i>批量删除';
    }
}

// 监听复选框变化
document.addEventListener('DOMContentLoaded', function() {
    const recordCheckboxes = document.querySelectorAll('.record-checkbox');
    recordCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateBatchDeleteButton();
            toggleRowSelection(this);
        });
    });
    
    // 添加键盘快捷键支持
    document.addEventListener('keydown', function(e) {
        // Ctrl+A 全选
        if (e.ctrlKey && e.key === 'a' && !e.target.matches('input, textarea')) {
            e.preventDefault();
            selectAll();
        }
        
        // Delete 键删除选中项
        if (e.key === 'Delete' && !e.target.matches('input, textarea')) {
            const checkedBoxes = document.querySelectorAll('.record-checkbox:checked');
            if (checkedBoxes.length > 0) {
                e.preventDefault();
                batchDelete();
            }
        }
        
        // Escape 键取消选择
        if (e.key === 'Escape') {
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            selectAllCheckbox.checked = false;
            toggleSelectAll();
        }
    });
});

// 切换行选中状态
function toggleRowSelection(checkbox) {
    const row = checkbox.closest('tr');
    if (checkbox.checked) {
        row.classList.add('selected');
    } else {
        row.classList.remove('selected');
    }
}

// 显示记录详情
function showLogDetail(logId) {
    const modal = new bootstrap.Modal(document.getElementById('logDetailModal'));
    const content = document.getElementById('logDetailContent');
    
    // 显示加载状态
    content.innerHTML = `
        <div class="text-center">
            <div class="loading-spinner"></div>
            <p class="mt-2">加载中...</p>
        </div>
    `;
    
    modal.show();
    
    // 通过AJAX获取详情数据
    fetch(`/inventory-logs/${logId}/detail/`, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const log = data.data;
                const quantityDisplay = log.transaction_type_code === 'in' 
                    ? `<span class="quantity-display quantity-in">+${log.quantity}</span>`
                    : `<span class="quantity-display quantity-out">-${log.quantity}</span>`;
                
                const transactionBadge = log.transaction_type_code === 'in'
                    ? `<span class="transaction-badge transaction-in"><i class="fas fa-arrow-down"></i> ${log.transaction_type}</span>`
                    : `<span class="transaction-badge transaction-out"><i class="fas fa-arrow-up"></i> ${log.transaction_type}</span>`;
                
                content.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-muted mb-3">
                                <i class="fas fa-info-circle me-1"></i>基本信息
                            </h6>
                            <table class="table table-borderless">
                                <tr>
                                    <td width="35%" class="text-muted">操作类型:</td>
                                    <td>${transactionBadge}</td>
                                </tr>
                                <tr>
                                    <td class="text-muted">耗材名称:</td>
                                    <td><strong class="text-primary">${log.consumable.name}</strong></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">耗材编码:</td>
                                    <td><code>${log.consumable.code}</code></td>
                                </tr>
                                ${log.consumable.model ? `
                                <tr>
                                    <td class="text-muted">规格型号:</td>
                                    <td><span class="badge bg-light text-dark">${log.consumable.model}</span></td>
                                </tr>
                                ` : ''}
                                ${log.consumable.category ? `
                                <tr>
                                    <td class="text-muted">耗材类别:</td>
                                    <td><span class="badge bg-info">${log.consumable.category}</span></td>
                                </tr>
                                ` : ''}
                                <tr>
                                    <td class="text-muted">数量变化:</td>
                                    <td>${quantityDisplay} <small class="text-muted">${log.consumable.unit}</small></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">库存余额:</td>
                                    <td>
                                        ${log.remaining_quantity !== null 
                                            ? `<span class="badge bg-light text-dark fs-6">${log.remaining_quantity} ${log.consumable.unit}</span>`
                                            : '<span class="text-muted">-</span>'
                                        }
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-muted mb-3">
                                <i class="fas fa-user-cog me-1"></i>操作信息
                            </h6>
                            <table class="table table-borderless">
                                <tr>
                                    <td width="35%" class="text-muted">操作人:</td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-user-circle me-2 text-info"></i>
                                            <div>
                                                <div class="fw-bold">${log.operator.name}</div>
                                                ${log.operator.username ? `<small class="text-muted">${log.operator.username}</small>` : ''}
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-muted">操作时间:</td>
                                    <td>
                                        <div class="d-flex flex-column">
                                            <span class="fw-bold">${log.created_date}</span>
                                            <small class="text-muted">${log.created_time}</small>
                                        </div>
                                    </td>
                                </tr>
                                ${log.warehouse.name ? `
                                <tr>
                                    <td class="text-muted">所属仓库:</td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-warehouse me-2 text-success"></i>
                                            <div>
                                                <div class="fw-bold">${log.warehouse.name}</div>
                                                ${log.warehouse.location ? `<small class="text-muted">${log.warehouse.location}</small>` : ''}
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                ` : ''}
                            </table>
                        </div>
                    </div>
                    <div class="mt-4">
                        <h6 class="text-muted mb-3">
                            <i class="fas fa-comment-alt me-1"></i>操作描述
                        </h6>
                        <div class="alert alert-light border-start border-primary border-4">
                            <div class="d-flex align-items-start">
                                <i class="fas fa-quote-left text-primary me-2 mt-1"></i>
                                <div class="flex-grow-1">
                                    ${log.description || '<em class="text-muted">暂无描述</em>'}
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                content.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        加载记录详情失败: ${data.error}
                    </div>
                `;
            }
        })
        .catch(error => {
            content.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    网络错误，请稍后重试
                </div>
            `;
            console.error('Error:', error);
        });
}

// 编辑描述
function editDescription(logId) {
    const modal = new bootstrap.Modal(document.getElementById('editDescriptionModal'));
    const row = document.querySelector(`tr[data-log-id="${logId}"]`);
    const descriptionText = row.querySelector('.description-text').textContent;
    
    document.getElementById('editLogId').value = logId;
    document.getElementById('editDescription').value = descriptionText === '暂无描述' ? '' : descriptionText;
    
    modal.show();
}

// 删除单条记录
function deleteLog(logId) {
    const row = document.querySelector(`tr[data-log-id="${logId}"]`);
    const consumableName = row.querySelector('td:nth-child(3) strong').textContent;
    const transactionType = row.querySelector('.transaction-badge').textContent.trim();
    
    // 创建确认对话框
    const confirmModal = document.createElement('div');
    confirmModal.className = 'modal fade';
    confirmModal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-triangle me-2"></i>确认删除
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>注意：</strong>删除记录后无法恢复，请谨慎操作！
                    </div>
                    <p class="mb-3">您确定要删除以下记录吗？</p>
                    <div class="card bg-light">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-sm-4 text-muted">耗材名称:</div>
                                <div class="col-sm-8"><strong>${consumableName}</strong></div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-sm-4 text-muted">操作类型:</div>
                                <div class="col-sm-8">${transactionType}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-danger" onclick="confirmDeleteLog(${logId})">
                        <i class="fas fa-trash me-1"></i>确认删除
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(confirmModal);
    const modal = new bootstrap.Modal(confirmModal);
    modal.show();
    
    // 模态框关闭后移除DOM元素
    confirmModal.addEventListener('hidden.bs.modal', function() {
        document.body.removeChild(confirmModal);
    });
}

// 确认删除记录
function confirmDeleteLog(logId) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = `
        {% csrf_token %}
        <input type="hidden" name="action" value="delete_log">
        <input type="hidden" name="log_id" value="${logId}">
    `;
    document.body.appendChild(form);
    form.submit();
}

// 批量删除
function batchDelete() {
    const checkedBoxes = document.querySelectorAll('.record-checkbox:checked');
    if (checkedBoxes.length === 0) {
        // 创建提示模态框
        const alertModal = document.createElement('div');
        alertModal.className = 'modal fade';
        alertModal.innerHTML = `
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-warning text-dark">
                        <h5 class="modal-title">
                            <i class="fas fa-exclamation-triangle me-2"></i>提示
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="text-center">
                            <i class="fas fa-info-circle fa-3x text-warning mb-3"></i>
                            <p class="mb-0">请先选择要删除的记录</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">知道了</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(alertModal);
        const modal = new bootstrap.Modal(alertModal);
        modal.show();
        
        alertModal.addEventListener('hidden.bs.modal', function() {
            document.body.removeChild(alertModal);
        });
        return;
    }
    
    // 获取选中记录的详细信息
    const selectedRecords = [];
    checkedBoxes.forEach(checkbox => {
        const row = document.querySelector(`tr[data-log-id="${checkbox.value}"]`);
        const consumableName = row.querySelector('td:nth-child(3) strong').textContent;
        const transactionType = row.querySelector('.transaction-badge').textContent.trim();
        selectedRecords.push({ id: checkbox.value, name: consumableName, type: transactionType });
    });
    
    // 创建批量删除确认对话框
    const confirmModal = document.createElement('div');
    confirmModal.className = 'modal fade';
    confirmModal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-triangle me-2"></i>批量删除确认
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>警告：</strong>您即将删除 <strong>${checkedBoxes.length}</strong> 条记录，此操作无法撤销！
                    </div>
                    <p class="mb-3">以下记录将被删除：</p>
                    <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
                        <table class="table table-sm table-striped">
                            <thead class="table-dark">
                                <tr>
                                    <th width="50%">耗材名称</th>
                                    <th width="50%">操作类型</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${selectedRecords.map(record => `
                                    <tr>
                                        <td><strong>${record.name}</strong></td>
                                        <td>${record.type}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-danger" onclick="confirmBatchDelete()">
                        <i class="fas fa-trash me-1"></i>确认删除 ${checkedBoxes.length} 条记录
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(confirmModal);
    const modal = new bootstrap.Modal(confirmModal);
    modal.show();
    
    // 模态框关闭后移除DOM元素
    confirmModal.addEventListener('hidden.bs.modal', function() {
        document.body.removeChild(confirmModal);
    });
}

// 确认批量删除
function confirmBatchDelete() {
    const checkedBoxes = document.querySelectorAll('.record-checkbox:checked');
    const form = document.createElement('form');
    form.method = 'POST';
    let formContent = '{% csrf_token %}<input type="hidden" name="action" value="batch_delete">';
    
    checkedBoxes.forEach(checkbox => {
        formContent += `<input type="hidden" name="log_ids" value="${checkbox.value}">`;
    });
    
    form.innerHTML = formContent;
    document.body.appendChild(form);
    form.submit();
}

// 导出记录
function exportRecords() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'excel');
    window.location.href = '?' + params.toString();
}

// 刷新数据
function refreshData() {
    const btn = event.target.closest('button');
    const originalContent = btn.innerHTML;
    
    btn.innerHTML = '<div class="loading-spinner me-1"></div>刷新中...';
    btn.disabled = true;
    
    setTimeout(() => {
        window.location.reload();
    }, 1000);
}

// 显示快速统计
function showQuickStats() {
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-chart-bar me-2"></i>快速统计分析
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h3 class="text-success">${{ total_in_logs|default:0 }}</h3>
                                    <p class="mb-0">入库记录总数</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h3 class="text-danger">${{ total_out_logs|default:0 }}</h3>
                                    <p class="mb-0">出库记录总数</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h3 class="text-warning">${{ today_logs|default:0 }}</h3>
                                    <p class="mb-0">今日操作记录</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h3 class="text-info">${{ total_logs|default:0 }}</h3>
                                    <p class="mb-0">记录总数</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4">
                        <h6 class="text-muted">操作提示</h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-keyboard text-primary me-2"></i><strong>Ctrl+A:</strong> 全选记录</li>
                            <li><i class="fas fa-keyboard text-primary me-2"></i><strong>Delete:</strong> 删除选中记录</li>
                            <li><i class="fas fa-keyboard text-primary me-2"></i><strong>Escape:</strong> 取消选择</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">知道了</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    const bootstrapModal = new bootstrap.Modal(modal);
    bootstrapModal.show();
    
    modal.addEventListener('hidden.bs.modal', function() {
        document.body.removeChild(modal);
    });
}

// 显示帮助信息
function showHelp() {
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-question-circle me-2"></i>使用帮助
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="accordion" id="helpAccordion">
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#help1">
                                    <i class="fas fa-search me-2"></i>如何搜索和筛选记录？
                                </button>
                            </h2>
                            <div id="help1" class="accordion-collapse collapse show" data-bs-parent="#helpAccordion">
                                <div class="accordion-body">
                                    <ul>
                                        <li>在搜索框中输入耗材名称或编码进行搜索</li>
                                        <li>使用下拉菜单筛选操作类型、操作人、仓库等</li>
                                        <li>选择时间范围查看特定时期的记录</li>
                                        <li>多个筛选条件可以组合使用</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#help2">
                                    <i class="fas fa-eye me-2"></i>如何查看记录详情？
                                </button>
                            </h2>
                            <div id="help2" class="accordion-collapse collapse" data-bs-parent="#helpAccordion">
                                <div class="accordion-body">
                                    <ul>
                                        <li>点击操作列中的"眼睛"图标查看详细信息</li>
                                        <li>详情包括耗材信息、操作人、时间、描述等</li>
                                        <li>可以查看库存余额变化情况</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#help3">
                                    <i class="fas fa-edit me-2"></i>如何编辑和删除记录？
                                </button>
                            </h2>
                            <div id="help3" class="accordion-collapse collapse" data-bs-parent="#helpAccordion">
                                <div class="accordion-body">
                                    <ul>
                                        <li>只有记录创建者或管理员可以编辑/删除记录</li>
                                        <li>点击描述旁的编辑图标可以修改操作描述</li>
                                        <li>点击删除按钮可以删除单条记录</li>
                                        <li>选中多条记录后可以批量删除</li>
                                        <li><strong>注意：</strong>删除操作无法撤销，请谨慎操作</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#help4">
                                    <i class="fas fa-download me-2"></i>如何导出记录？
                                </button>
                            </h2>
                            <div id="help4" class="accordion-collapse collapse" data-bs-parent="#helpAccordion">
                                <div class="accordion-body">
                                    <ul>
                                        <li>点击"导出记录"按钮可以导出当前筛选结果</li>
                                        <li>导出格式为Excel文件</li>
                                        <li>包含所有可见的记录信息</li>
                                        <li>可以先筛选再导出特定数据</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    const bootstrapModal = new bootstrap.Modal(modal);
    bootstrapModal.show();
    
    modal.addEventListener('hidden.bs.modal', function() {
        document.body.removeChild(modal);
    });
}

// 自动提交筛选表单
document.addEventListener('DOMContentLoaded', function() {
    const filterForm = document.getElementById('filterForm');
    const selects = filterForm.querySelectorAll('select');
    
    selects.forEach(select => {
        select.addEventListener('change', function() {
            filterForm.submit();
        });
    });
    
    // 搜索框延迟提交
    const searchInput = document.getElementById('search');
    let searchTimeout;
    
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            filterForm.submit();
        }, 500);
    });
    
    // 添加页面加载完成提示
    const toast = document.createElement('div');
    toast.className = 'toast position-fixed bottom-0 end-0 m-3';
    toast.innerHTML = `
        <div class="toast-header">
            <i class="fas fa-check-circle text-success me-2"></i>
            <strong class="me-auto">系统提示</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            耗材记录管理页面已加载完成
        </div>
    `;
    
    document.body.appendChild(toast);
    const bootstrapToast = new bootstrap.Toast(toast, { delay: 3000 });
    bootstrapToast.show();
    
    toast.addEventListener('hidden.bs.toast', function() {
        document.body.removeChild(toast);
    });
});
</script>
{% endblock %}